package server;

import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Mapper {

    private List<Host> host = new ArrayList<>();

    public Mapper() {

    }


    public void addHost(Host host) {
        this.host.add(host);
    }

    public List<Context> getContext() {
        List<Context> list = new ArrayList<>();
        for (Host h : host) {
            list.add(h.context);
        }
        return list;
    }

    /**
     * 根据请求 url 查询 servlet
     * @param url
     * @return
     */
    public Wrapper find(String url) {
        System.out.println("find " + url);
        for (Host h: host) {
             if (url.startsWith("/" + h.context.serverName)) {
                 return h.context.getWrapper(url);
             }
        }
        return null;
    }

    /**
     * 查找静态资源
     * @param url
     * @return
     */
    public String findStatic(String url) {
        System.out.println("find static resources " + url);
        for (Host h: host) {
            if (url.startsWith("/" +  h.context.serverName)) {
                return h.context.appBase + File.separator + url;
            }
        }
        return "";
    }

//    public void addWrapper(Wrapper wrapper) {
//        this.host.context.addWrapper(wrapper);
//    }
//
//    public String getAppBase() {
//        return this.host.context.appBase;
//    }
//
//    public Wrapper getWrapper(String url) {
//        return this.host.context.getWrapper(url);
//    }



    static class Host {
        String hostName;
        Context context;

        public Host(String hostName, Context context) {
            this.hostName = hostName;
            this.context = context;
        }
    }

    static class Context {
       String appBase; // appBase 目录
       String serverName; // 项目名称
       Map<String, Wrapper> map = new HashMap<>();

        public Context(String appBase, String serverName) {
            this.appBase = appBase;
            this.serverName = serverName;
        }

        public void addWrapper(Wrapper wrapper) {
            map.put(wrapper.url, wrapper);
        }

        public Wrapper getWrapper(String url) {
            return this.map.get(url);
        }
    }

    static class Wrapper {
       String url; // 访问的 url
       Servlet servlet;

        public Wrapper(String url, Servlet servlet) {
            this.url = url;
            this.servlet = servlet;
        }
    }


}
